package org.kev.transit;



import org.kev.transit.util.TransitConst;
import org.kev.transit.worker.LocOverlay;
import org.kev.transit.worker.MapWorker;

import com.google.android.maps.MapView;
import com.google.android.maps.MapController;
import com.google.android.maps.MapActivity;
import com.google.android.maps.OverlayController;
import com.google.android.maps.Point;


import android.app.AlertDialog;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class TransitMapActivity extends MapActivity implements Navigateable{
	static final private int ABOUT_ID =  Menu.FIRST;

	static final private int FIND_LOC_ID =  Menu.FIRST + 2;
	static final private int ZOOM_IN_ID =  Menu.FIRST+ 3;
	static final private int ZOOM_OUT_ID =  Menu.FIRST + 4;
	static final private int SAT_VIEW_ID =  Menu.FIRST+ 5;
	static final private int TRAFFIC_VIEW_ID = Menu.FIRST + 6;

	static final private int DEFAULT_ZOOM = 15;
	static final private int DEFAULT_ZOOM_MAP = 13;
	private static final String TAG = "TransitMapActivity";
	private MapView mapView = null;
	private MapController mControl = null;
	public OverlayController overlayControl = null;
	protected LocationManager locManager = null;
	protected Location currentLoc = null;
	private int zoomLevel = DEFAULT_ZOOM;
	private MapWorker mapWorker = null;
	public Point stationGPS = null;
	public LocOverlay overlay = null;
	protected Handler mHandler= new Handler();

	public TransitMapActivity() {

	}

	/**
	 * Called when fist started
	 * 
	 * @param icicle
	 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		try {
	        requestWindowFeature(Window.FEATURE_PROGRESS);
			setContentView(R.layout.tmap);
	        setProgressBarVisibility(true);
	        setProgressBarIndeterminate(true);		
			mapView = (MapView) findViewById(R.id.gMapView);
			mapView.setOnClickListener(mLinkListener);
			TextView view = (TextView) findViewById(R.id.ad_wordLabel);
			Log.d(TAG,"view="+view);
			view.setOnClickListener(mLinkListener);
			view.setFocusable(true);
	//		view.setEnabled(true);
			mControl = mapView.getController();
			overlayControl = mapView.createOverlayController();
			
			double dlat = TransitConf.currentLat;
			double dlong = TransitConf.currentLon;

			Log.d(TransitConst.TAG, "flat=" + dlat);
			Log.d(TransitConst.TAG, "flong=" + dlong);
			int ilat = getMLat(dlat);
			int ilong = getMLong(dlong);
			Log.d(TAG, "ilat=" + ilat);
			Log.d(TAG, "ilong=" + ilong);
			stationGPS = new Point(ilat, ilong);
			mControl.centerMapTo(stationGPS, false);

			mControl.zoomTo(zoomLevel);
			setProgressBarVisibility(false);
		} catch (Exception e) {
			Log.e(TransitConst.TAG, "UKNOWN Error in " + this, e);
			AlertDialog.show(this, "StackTrace", 1,e.getMessage(), "Ok", false);
		}
	}

	/**
	 * Called to remember the current state before the activity stops.
	 */
	@Override
	protected void onFreeze(Bundle outState) {
		super.onFreeze(outState);

		// Save the current text editor state. As noted above in
		// onCreate(), this is somewhat unusual in that our text
		// is not in persistent storage. If we did have it in persistent
		// storage, we would call mEditor.saveState() here instead.
		// outState.putBundle("text", mEditor.saveStateAndText());
	}

	/**
	 * Called when your activity's options menu needs to be created.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// We are going to create two menus. Note that we assign them
		// unique integer IDs, labels from our string resources, and
		// given them shortcuts.
		menu.add(0, ABOUT_ID, R.string.about_menu).setShortcut('1', 'a');
		menu.add(0, FIND_LOC_ID, R.string.findLoc).setShortcut('2', 'l');
		menu.add(0, ZOOM_IN_ID, R.string.zoomIn).setShortcut('3','i');
		menu.add(0, ZOOM_OUT_ID, R.string.zoomOut).setShortcut('4','o');
		menu.add(0, SAT_VIEW_ID, R.string.satView).setShortcut('5','s');
		menu.add(0, TRAFFIC_VIEW_ID, R.string.trafficView).setShortcut('6','t');

		return true;
	}

	/**
	 * Called right before your activity's option menu is displayed.
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		// Before showing the menu, we need to decide whether the clear
		// item is enabled depending on whether there is text to clear.
		// menu.setItemShown(CLEAR_ID, mEditor.getText().length() > 0);

		return true;
	}
	private void linkClick(){
		startActivity(TransitConst.BROWSER_INTENT );
		
	}

	/**
	 * Called when a menu item is selected.
	 */
	@Override
	public boolean onOptionsItemSelected(Menu.Item item) {
		switch (item.getId()) {
		case ABOUT_ID:
			aboutScreen();
			return true;
		case FIND_LOC_ID:
			 setProgressBarVisibility(true); 
			mapWorker= new MapWorker(this,mUpdateResults,mHandler);
			Thread t = new Thread(mapWorker);
			t.start(); // call mapLocation();

			return true;
		case ZOOM_IN_ID:
			Log.d(TransitConst.TAG, "before zoom leve=" + zoomLevel);
			if (zoomLevel < 20) { // 21 is current max zoom
				zoomLevel++;
				Log.d(TransitConst.TAG, "zoom leve=" + zoomLevel);
				mControl.zoomTo(zoomLevel);
			}
			return true;
		case SAT_VIEW_ID:
			// Switch on the satellite images
			mapView.toggleSatellite();
			return true;
		case TRAFFIC_VIEW_ID:
			// Switch on traffic
			mapView.toggleTraffic();

			return true;
		case ZOOM_OUT_ID:
			Log.d(TransitConst.TAG, "before zoom leve=" + zoomLevel);
			if (zoomLevel > 0) {
				zoomLevel--;
				mControl.zoomTo(zoomLevel);

			}

			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * convert latitude to a flat map integer value
	 * 
	 * @param latitude
	 * @return latitude that was translated
	 */
	public int getMLat(double latitude) {
		Double d = latitude * 1E6;
		return d.intValue();
	}

	/**
	 * convert latitude to a flat map integer value
	 * 
	 * @param longitude
	 * @return longitude that is translated
	 */
	public int getMLong(double longitude) {
		Double d = longitude * 1E6;
		return d.intValue();
	}

	protected void mapLocation() {
		// Log.d(TAG,"span========"+overlay.getLatSpanE6()+"/"+overlay.getLonSpanE6());
		int lon = overlay.getLonSpanE6();
		mControl.zoomToSpan(overlay.getLatSpanE6(), lon);
		double d = lon /1E6;
		
		//try to guess zoom level
		Log.d(TAG,"degree of long="+d);
		d = (Math.abs(d));
		Log.d(TAG,"degree of long="+d);
		d= (256/360)*d;
		Log.d(TAG,"guess zoom="+d);
		zoomLevel = DEFAULT_ZOOM_MAP;
		mControl.animateTo(overlay.getCenter());
	}
	public void aboutScreen() {
		
			String title= this.getResources().getString(R.string.about_title);
			String text= this.getResources().getString(R.string.about_text);
			String ok=getResources().getString(R.string.about_ok);
			AlertDialog.show(this, title,1, text, ok, true);
	}

	public void nextScreen() {
		//no next screen now
		//might call web browser with link to add 
		
	}
    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        
        public void run() {
        	mapLocation();
        	 setProgressBarVisibility(false); 
        }
    };
	/***
	 * A call-back for when the user presses on a link
	 */
	OnClickListener mLinkListener = new OnClickListener() {
		public void onClick(View v) {
			Log.d(TAG,"Link clicked");
			linkClick();

		}
	};




}
